package com.mm.cloud.common.mq.service.impl;

import com.mm.cloud.common.mq.message.CustomMessage;
import com.mm.cloud.common.mq.message.RabbitMessage;
import com.mm.cloud.common.mq.service.IMqService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * MQ服务实现
 *
 * @author mr
 * @since 2021-09-15
 */
@Slf4j
@Component
public class MqServiceImpl implements IMqService {

    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public MqServiceImpl(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("消息发送到exchange成功,id: {}", correlationData.getId());
            } else {
                log.error("消息发送到exchange失败,原因: {}", cause);
            }
        });
//        this.rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
//            String correlationId = message.getMessageProperties().getCorrelationId();
//            log.error("消息：{} 发送失败, 应答码：{} 原因：{} 交换机: {}  路由键: {}", correlationId, replyCode, replyText, exchange,
//                    routingKey);
//        });
    }


    @Override
    public void send(RabbitMessage<?> message) {
        rabbitTemplate.convertAndSend(
                message.getExchange().getKey(),
                message.getRoutingKey().getKey(),
                new CustomMessage(message.getUuid(), message.getData()),
                new CorrelationData(message.getUuid()));
    }

}
